import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/common/xindong_define.dart';
import 'package:xindong/common/xindong_all.dart';
import 'package:xindong/handle/xindong_user_handle.dart';
import 'package:xindong/manager/xindong_page_singleton.dart';
import 'package:xindong/routes/common/xindong_input_text_yemian.dart';
import 'package:xindong/routes/conversation/model/xindong_liaotian_detail_class.dart';
import 'package:xindong/routes/tab_chats/controller/xindong_liaotian_vm.dart';
import 'package:xindong/utils/xindong_text_util.dart';
import 'package:xindong/widgets/common/xindong_app_bar.dart';
import 'package:xindong/widgets/dialog/xindong_alert_message.dart';
import 'package:xindong/widgets/xindong_avatar.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';

class XinDongLiaoTianSettingYeMian extends StatefulWidget {
  final V2TimConversation conversation;
  final XinDongLiaoTianDetailClass detailClass;
  final Function() onTapAvatar;

  const XinDongLiaoTianSettingYeMian(
      {super.key, required this.conversation, required this.detailClass, required this.onTapAvatar});

  @override
  State<XinDongLiaoTianSettingYeMian> createState() => _XinDongLiaoTianSettingYeMianState();
}

class _XinDongLiaoTianSettingYeMianState extends State<XinDongLiaoTianSettingYeMian> {
  V2TimFriendInfoResult? friendInfoResult;

  bool get isFriend {
    return friendInfoResult?.relation == 1 || friendInfoResult?.relation == 3;
  }

  String get friendRemark {
    return friendInfoResult?.friendInfo?.friendRemark ?? "";
  }

  Future<void> getFriendsInfo() async {
    String userId = widget.detailClass.another.uid;
    V2TimValueCallback<List<V2TimFriendInfoResult>> result =
        await TencentImSDKPlugin.v2TIMManager.getFriendshipManager().getFriendsInfo(userIDList: [userId]);
    if (result.code == 0 && result.data != null && result.data!.isNotEmpty) {
      V2TimFriendInfoResult friendInfoResult = result.data!.first;
      // relation;//好友类型 0:不是好友 1:对方在我的好友列表中 2:我在对方的好友列表中 3:互为好友
      // friendRemark;//好友备注
      // userProfile?.nickName;//用户昵称
      // userProfile?.userID;//用户 ID
      // print("objectmmmmm ${friendInfoResult.relation}");
      // print("objectmmmmm ${friendInfoResult.friendInfo?.friendRemark}");
      this.friendInfoResult = friendInfoResult;
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();

    getFriendsInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: XinDongAppBar("资料"),
      body: ListView(
        children: [
          GestureDetector(
            onTap: widget.onTapAvatar,
            child: Container(
              height: 90,
              color: DZColors.cellColor,
              padding: const EdgeInsets.only(left: kPaddingValue, right: 10),
              margin: const EdgeInsets.only(bottom: 1.0),
              child: Row(
                children: [
                  XinDongAvatar(url: widget.detailClass.another.getAvatar, size: 70, radius: 8),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          widget.detailClass.another.getName,
                          style: const TextStyle(fontSize: 16, color: DZColors.titleColor),
                        ),
                        const SizedBox(height: 5),
                        Text(
                          "备注：$friendRemark",
                          style: const TextStyle(fontSize: 15, color: DZColors.placeholderColor),
                        ),
                      ],
                    ),
                  ),
                  XinDongAll.instance.defaultIconNext,
                ],
              ),
            ),
          ),
          const SizedBox(height: 10),
          _buildItem(
            title: '设置备注',
            onTap: () {
              XinDongPageSingleton.instance.pushYeMian(XinDongInputTextYeMian(
                inputEnum: XinDongInputProfileEnum.remark,
                value: friendRemark,
                doneCallback: (String text) {
                  String userId = widget.detailClass.another.uid;
                  if (isFriend) {
                    if (text.isEmpty) {
                      TencentImSDKPlugin.v2TIMManager.getFriendshipManager().deleteFromFriendList(
                        userIDList: [userId],
                        deleteType: FriendTypeEnum.V2TIM_FRIEND_TYPE_SINGLE,
                      ).then((result) {
                        if (result.code == 0) {
                          // widget.conversation.showName = !widget.conversation.isPinned!;
                          getFriendsInfo();
                        } else {
                          showToast("${result.code} ${result.desc}");
                        }
                      });
                    } else {
                      TencentImSDKPlugin.v2TIMManager
                          .getFriendshipManager()
                          .setFriendInfo(userID: userId, friendRemark: text)
                          .then((V2TimCallback result) {
                        if (result.code == 0) {
                          // widget.conversation.showName = !widget.conversation.isPinned!;
                          getFriendsInfo();
                        } else {
                          showToast("${result.code} ${result.desc}");
                        }
                      });
                    }
                  } else {
                    TencentImSDKPlugin.v2TIMManager
                        .getFriendshipManager()
                        .addFriend(userID: userId, remark: text, addType: FriendTypeEnum.V2TIM_FRIEND_TYPE_SINGLE)
                        .then((V2TimValueCallback<V2TimFriendOperationResult> result) {
                      if (result.code == 0) {
                        getFriendsInfo();
                      } else {
                        showToast("${result.code} ${result.desc}");
                      }
                    });
                  }
                },
              ));
            },
          ),
          const SizedBox(height: 10),
          _buildItem(
            title: '置顶聊天',
            rightView: CupertinoSwitch(
              value: widget.conversation.isPinned ?? false,
              activeColor: DZColors.mainColor,
              onChanged: (enable) async {
                bool result = await XinDongLiaoTianVM.to.requestPinConversation(widget.conversation);
                if (result) {
                  widget.conversation.isPinned = !widget.conversation.isPinned!;
                  setState(() {});
                }
              },
            ),
          ),
          _buildItem(
            title: '拉黑用户',
            rightView: CupertinoSwitch(
              value: widget.detailClass.data.blacklist == 1,
              activeColor: DZColors.mainColor,
              onChanged: (enable) async {
                bool result = await XinDongUserHandle().blackListAdd(userId: widget.detailClass.another.uid);
                if (result) {
                  if (widget.detailClass.data.blacklist == 1) {
                    widget.detailClass.data.blacklist = 0;
                  } else {
                    widget.detailClass.data.blacklist = 1;
                  }
                  setState(() {});
                }
              },
            ),
          ),
          _buildItem(
            title: '关注用户',
            rightView: CupertinoSwitch(
              value: widget.detailClass.data.attention == 1,
              activeColor: DZColors.mainColor,
              onChanged: (enable) async {
                bool result = await XinDongUserHandle().attention(userId: widget.detailClass.another.uid);
                if (result) {
                  if (widget.detailClass.data.attention == 1) {
                    widget.detailClass.data.attention = 0;
                  } else {
                    widget.detailClass.data.attention = 1;
                  }
                  setState(() {});
                }
              },
            ),
          ),
          const SizedBox(height: 10),
          _buildItem(
            title: '清空聊天记录',
            onTap: () {
              XinDongAlertMessage.show(
                title: "提示",
                content: "确定要删除和Ta的聊天记录吗？\n删除记录不会删除会话列表",
                onTapButton: () {
                  XinDongLiaoTianVM.to.requestClearC2CMessages(widget.conversation);
                },
              );
            },
          ),
          _buildItem(
            title: '举报',
            onTap: () {
              XinDongPageSingleton.instance.jumpToReport(userId: widget.detailClass.another.uid);
            },
          ),
        ],
      ),
    );
  }

  Widget _buildItem({required String title, Widget? rightView, Function()? onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: kCellHeight,
        color: DZColors.cellColor,
        padding: const EdgeInsets.only(left: kPaddingValue, right: 10),
        margin: const EdgeInsets.only(bottom: 1.0),
        child: Row(
          children: [
            Expanded(
              child: Text(
                title,
                style: const TextStyle(fontSize: 16, color: DZColors.titleColor),
              ),
            ),
            rightView ?? XinDongAll.instance.defaultIconNext,
          ],
        ),
      ),
    );
  }
}
